local base = _G
local string = require "string"
local http = require "socket.http"
local redis = require "resty.redis"
local ngx  = ngx
module("weibo.util")

UUID_URL="http://192.168.5.23/idgenerator"

default_node = {
   ["path"] = "unix:/tmp/redis.sock",
   ["host"] = "127.0.0.1",
   ["port"] = 6379
}

function getUUID()
  --if 1 then return 3232 end
  local uuid , code = getURL(UUID_URL)
  if code ~= 200 then
     ngx.log(ngx.ERR,"getUUID error,please check the url:" .. UUID_URL)
     return -1,"getUUID error"
  end
  return uuid
end


function getURL(url)
  local res, code, headers , status = http.request(UUID_URL)
  if code ~= 200 then
     --base.error("getURL" .. url ,2)
     ngx.log(ngx.ERR,"getURL error:" .. status)
     return status,code
  end
  return res,code
end


function do_exec_redis (node,cmd,args)
  local red = redis:new()
  local ok , err , res

  red:set_timeout(1000) -- 1 sec

  if not node then 
      ngx.log(ngx.ERR,"#exec_redis invalid param")
      return nil , err
  end

  
  ngx.log(ngx.DEBUG,"do_exec_redis node:", node.path,node.host,node.port)

  if node.path then
     ok, err = red:connect(node.path)
  else
     ok, err = red:connect(node.host,node.port)
  end 

  if not ok then
      ngx.log(ngx.ERR,"failed to connect: ", err)
      return nil , err
  end


  res, err = red[cmd](red,base.unpack(args))
  if not res then
     ngx.log(ngx.ERR,"redis exec " .. cmd .. " err:", err)
     return nil , err
  end

  -- put it into the connection pool of size 100,
  -- with 0 idle timeout
  ok, err = red:set_keepalive(0, 100)
  if not ok then
      ngx.log(ngx.ERR,"failed to set keepalive: ", err)
      return nil , err
  end
 
  return res
end

function redis_eval (...)
 local args = {...}
 local node = default_node
 if base.type(args[1]) == "table" then
    node = args[1]
    base.table.remove(args,1) 
 end
 return  do_exec_redis (node,"eval",args)
end



function table_tostring(t)
 local res = "{"
 for k,v in base.pairs(t) do
  res = base.string.format("%s [\"%s\"]=\"%s\", ",res,k,v)
 end
 res = base.string.format("%s }",res)
 return res
end
